package com.cnt.controller.convertor;

import org.modelmapper.Converter;
import org.modelmapper.spi.MappingContext;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class StringToDateConverter implements Converter<String, Date> {

    private final DateFormat dateFormat;

    public StringToDateConverter(String dateFormat) {
        this.dateFormat = new SimpleDateFormat(dateFormat);
    }

    @Override
    public Date convert(MappingContext<String, Date> context) {
        try {
            return dateFormat.parse(context.getSource());
        } catch (Exception e) {
            throw new IllegalStateException("Failed to parse date " + context.getSource(), e);
        }
    }

}
